package com.example.redis6.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.redis6.dao.ProductDao;
import com.example.redis6.model.ProductDo;
import com.example.redis6.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * description: ProductServiceImpl <br>
 * date: 2021/7/22 13:31 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    @Override
    public int save(ProductDo productDo) {
        return productDao.insert(productDo);
    }

    @Override
    @CacheEvict(value = {"product"},key = "#root.args[0]")
    public int delById(int id) {
        return productDao.deleteById(id);
    }

    @Override
    @CachePut(value = {"product"},key = "#productDo.id")
    public ProductDo updateById(ProductDo productDo) {
        productDao.updateById(productDo);
        return productDo;
    }

    @Override
    @Cacheable(value = {"product"} ,key = "#root.args[0]" ,cacheManager = "cacheManager1Day",sync = true)
    public ProductDo findById(int id) {
        return productDao.selectById(id);
    }

    @Override
    @Cacheable(value = {"product_page"},keyGenerator = "springCacheDefaultKeyGenerator",cacheManager = "cacheManager1Day",sync = true)
    public Map<String, Object> page(int page, int size) {
        Page pageInfo = new Page(page, size);
        IPage<ProductDo> iPage = productDao.selectPage(pageInfo, null);

        Map<String,Object> pageMap = new HashMap<>();

        pageMap.put("total_record",iPage.getTotal());
        pageMap.put("total_page",iPage.getPages());
        pageMap.put("cuttent_date",iPage.getRecords());

        return pageMap;
    }
}
